// activity.js
const { runAsync, allAsync, getAsync, retryOperation, log } = require('./dbConfig');

/**
 * 新增活动
 * @param {Object} req - 请求对象，包含活动信息
 * @param {Object} res - 响应对象
 */
const addActivity = async (req, res) => {
  const { activity_date, activity_theme, activity_addr, activity_content, participate_users_id, participate_users_name, leave_users_id, leave_users_name, create_user } = req.body;
  if (!activity_date || !activity_theme) {
    return res.status(500).json({ success: false, msg: '日期和活动主题为必填项', code: '1', data: [] });
  }

  try {
    await retryOperation(() =>
      runAsync(
        `INSERT INTO sk_activity (activity_date, activity_theme, activity_addr, activity_content, participate_users_id, participate_users_name, leave_users_id, leave_users_name, create_user) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [activity_date, activity_theme, activity_addr, activity_content, participate_users_id, participate_users_name, leave_users_id, leave_users_name, create_user]
      )
    );
    const result = await getAsync(`SELECT last_insert_rowid() as id`);
    const lastID = result.id;
    log(`Inserted ID: ${lastID}`);
    res.json({ success: true, msg: '新增成功', code: '0', data: [lastID] });
  } catch (err) {
    log(`新增活动失败: ${err.message}`);
    res.status(500).json({ success: false, msg: '新增活动信息失败，请稍后再试', code: '1', data: [] });
  }
};

/**
 * 修改活动信息
 * @param {Object} req - 请求对象，包含更新信息和 ID
 * @param {Object} res - 响应对象
 */
const updateActivity = async (req, res) => {
  const { id, activity_date, activity_theme, activity_addr, activity_content, participate_users_id, participate_users_name, leave_users_id, leave_users_name, update_user } = req.body;

  try {
    await retryOperation(() =>
      runAsync(
        `UPDATE sk_activity SET activity_date = ?, activity_theme = ?, activity_addr = ?, activity_content = ?, participate_users_id = ?, participate_users_name = ?, leave_users_id = ?, leave_users_name = ?, update_user = ?, update_time = CURRENT_TIMESTAMP WHERE id = ? AND del_flag = '0'`,
        [activity_date, activity_theme, activity_addr, activity_content, participate_users_id, participate_users_name, leave_users_id, leave_users_name, update_user, id]
      )
    );
    res.json({ success: true, msg: '修改成功', code: '0', data: [] });
  } catch (err) {
    log(`修改活动失败: ${err.message}`);
    res.status(500).json({ success: false, msg: '修改活动信息失败，请稍后再试', code: '1', data: [] });
  }
};

/**
 * 删除活动（逻辑删除）
 * @param {Object} req - 请求对象，包含 ID
 * @param {Object} res - 响应对象
 */
const deleteActivity = async (req, res) => {
  const { id } = req.params;

  try {
    await retryOperation(() =>
      runAsync(`UPDATE sk_activity SET del_flag = '1' WHERE id = ?`, [id])
    );
    res.json({ success: true, msg: '删除成功', code: '0', data: [] });
  } catch (err) {
    log(`删除活动失败: ${err.message}`);
    res.status(500).json({ success: false, msg: '删除活动信息失败，请稍后再试', code: '1', data: [] });
  }
};

/**
 * 查询活动列表（带搜索条件和分页）
 * @param {Object} req - 请求对象，包含搜索条件和分页参数
 * @param {Object} res - 响应对象
 */
const getPageActivityList = async (req, res) => {
  const { activity_date, activity_theme, activity_addr, participate_users_id, leave_users_id, page, size } = req.query;

  const pageNum = parseInt(page) || 1; // 默认第 1 页
  const pageSize = parseInt(size) || 10; // 默认每页 10 条

  let query = 'SELECT *, CONCAT(COALESCE((LENGTH(participate_users_id) - LENGTH(REPLACE(participate_users_id, \',\', \'\')) + 1), 0), \'人\') AS participate_count, CONCAT(COALESCE((LENGTH(leave_users_id) - LENGTH(REPLACE(leave_users_id, \',\', \'\')) + 1), 0), \'人\') AS leave_count FROM sk_activity WHERE del_flag = \'0\'';
  let countQuery = 'SELECT COUNT(*) as total FROM sk_activity WHERE del_flag = \'0\'';
  const params = [];
  const countParams = [];

  if (activity_date) {
    query += ' AND activity_date LIKE ?';
    countQuery += ' AND activity_date LIKE ?';
    params.push(`%${activity_date}%`);
    countParams.push(`%${activity_date}%`);
  }

  if (activity_theme) {
    query += ' AND activity_theme LIKE ?';
    countQuery += ' AND activity_theme LIKE ?';
    params.push(`%${activity_theme}%`);
    countParams.push(`%${activity_theme}%`);
  }

  if (activity_addr) {
    query += ' AND activity_addr LIKE ?';
    countQuery += ' AND activity_addr LIKE ?';
    params.push(`%${activity_addr}%`);
    countParams.push(`%${activity_addr}%`);
  }

  if (participate_users_id) {
    query += ' AND participate_users_id LIKE ?';
    countQuery += ' AND participate_users_id LIKE ?';
    params.push(`%${participate_users_id}%`);
    countParams.push(`%${participate_users_id}%`);
  }

  if (leave_users_id) {
    query += ' AND leave_users_id LIKE ?';
    countQuery += ' AND leave_users_id LIKE ?';
    params.push(`%${leave_users_id}%`);
    countParams.push(`%${leave_users_id}%`);
  }

  query += ' ORDER BY id DESC LIMIT ? OFFSET ?';
  params.push(pageSize, (pageNum - 1) * pageSize);

  try {
    const rows = await allAsync(query, params);
    const countRow = await getAsync(countQuery, countParams);
    res.json({ data: rows, code: '0', success: true, msg: '获取列表成功', total: countRow.total });
  } catch (err) {
    log(`Get activity list error: ${err.message}`);
    res.status(500).json({ error: err.message });
  }
};

/**
 * 查询活动列表（带搜索条件不分页）
 * @param {Object} req - 请求对象，包含搜索条件
 * @param {Object} res - 响应对象
 */
const getActivityList = async (req, res) => {
  const { activity_date, activity_theme, activity_addr, participate_users_id, leave_users_id } = req.query;

  let query = 'SELECT *, CONCAT(COALESCE((LENGTH(participate_users_id) - LENGTH(REPLACE(participate_users_id, \',\', \'\')) + 1), 0), \'人\') AS participate_count, CONCAT(COALESCE((LENGTH(leave_users_id) - LENGTH(REPLACE(leave_users_id, \',\', \'\')) + 1), 0), \'人\') AS leave_count FROM sk_activity WHERE del_flag = \'0\'';
  let countQuery = 'SELECT COUNT(*) as total FROM sk_activity WHERE del_flag = \'0\'';
  const params = [];
  const countParams = [];

  if (activity_date) {
    query += ' AND activity_date LIKE ?';
    countQuery += ' AND activity_date LIKE ?';
    params.push(`%${activity_date}%`);
    countParams.push(`%${activity_date}%`);
  }

  if (activity_theme) {
    query += ' AND activity_theme LIKE ?';
    countQuery += ' AND activity_theme LIKE ?';
    params.push(`%${activity_theme}%`);
    countParams.push(`%${activity_theme}%`);
  }

  if (activity_addr) {
    query += ' AND activity_addr LIKE ?';
    countQuery += ' AND activity_addr LIKE ?';
    params.push(`%${activity_addr}%`);
    countParams.push(`%${activity_addr}%`);
  }

  if (participate_users_id) {
    query += ' AND participate_users_id LIKE ?';
    countQuery += ' AND participate_users_id LIKE ?';
    params.push(`%${participate_users_id}%`);
    countParams.push(`%${participate_users_id}%`);
  }

  if (leave_users_id) {
    query += ' AND leave_users_id LIKE ?';
    countQuery += ' AND leave_users_id LIKE ?';
    params.push(`%${leave_users_id}%`);
    countParams.push(`%${leave_users_id}%`);
  }

  query += ' ORDER BY id DESC';

  try {
    const rows = await allAsync(query, params);
    const countRow = await getAsync(countQuery, countParams);
    res.json({ data: rows, code: '0', success: true, msg: '获取列表成功', total: countRow.total });
  } catch (err) {
    log(`获取活动信息列表失败: ${err.message}`);
    res.status(500).json({ success: false, msg: '获取活动列表失败，请刷新重试', code: '1', data: [] });
  }
};

/**
 * 查询活动详情
 * @param {Object} req - 请求对象，包含 ID
 * @param {Object} res - 响应对象
 */
const queryActivityDetail = async (req, res) => {
  const { id } = req.params;

  try {
    const row = await getAsync('SELECT * FROM sk_activity WHERE id = ? AND del_flag = \'0\'', [id]);
    if (!row) {
      return res.status(500).json({ success: false, msg: '未查询到活动信息', code: '1', data: [] });
    }
    res.json({ data: row, code: '0', success: true, msg: '查询详情成功' });
  } catch (err) {
    log(`Get activity detail error: ${err.message}`);
    res.status(500).json({ error: err.message });
  }
};

// 模块导出
module.exports = { addActivity, updateActivity, deleteActivity, getPageActivityList, getActivityList, queryActivityDetail };